//
//  AppDelegate.m
//  UIScrollView的快速使用
//
//  Created by YQ05 on 2018/7/17.
//  Copyright © 2018年 YQ05. All rights reserved.
//

#import "AppDelegate.h"
#import "ViewController.h"
//#import "LandingPageVC.h"
#import "Notification/MyViewController.h"
#import "testVc2.h"
#import "DB/DataPersist.h"

#import "setLocalnoti.h"
#import "SetLocalnotiVC.h"

//#import <Firebase/Firebase.h>
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
#import <UserNotifications/UserNotifications.h>
#endif

@import UserNotifications;

@interface AppDelegate ()<UNUserNotificationCenterDelegate>{
    NSDictionary *imageCache;
}

@end



@implementation AppDelegate


NSString *const kGCMMessageIDKey = @"gcm.message_id";
//NSString *const type = @"";
//NSString *const api = @"";

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
     //Override point for customization after application launch.
    ViewController *loginVC = [[ViewController alloc]init];
    //LandingPageVC *loginVC = [[LandingPageVC alloc]init];
    UINavigationController *NavVC = [[UINavigationController alloc]initWithRootViewController:loginVC];
    self.window.rootViewController = NavVC;
    [self.window makeKeyAndVisible];
    
    
    /**
     本地推送 app 死亡模式
     */
//    if (launchOptions[UIApplicationLaunchOptionsLocalNotificationKey]) {
//        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 414, 736)];
//        label.backgroundColor = [UIColor greenColor];
//        label.numberOfLines = 0;
//        UILocalNotification *local = launchOptions[UIApplicationLaunchOptionsLocalNotificationKey];
//        label.text = [NSString stringWithFormat:@"%@",local.userInfo];
//        [self.window.rootViewController.view addSubview:label];
//
//    }
    
    /**
     远程推送
     */
    UIUserNotificationSettings *settting = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge|UIUserNotificationTypeSound|UIUserNotificationTypeAlert categories:nil];
    [[UIApplication sharedApplication]registerForRemoteNotifications];
    [[UIApplication sharedApplication]registerUserNotificationSettings:settting];
    
    [FIRApp configure];
    
    // [START set_messaging_delegate]
    [FIRMessaging messaging].delegate = self;
    // [END set_messaging_delegate]
    
    //if ([UNUserNotificationCenter class] != nil) {
   if (@available(iOS 10.0, *)) {  //and
       if ([UNUserNotificationCenter class] != nil) {
           // iOS 10 or later
           // For iOS 10 display notification (sent via APNS)
           [UNUserNotificationCenter currentNotificationCenter].delegate = self;
           UNAuthorizationOptions authOptions = UNAuthorizationOptionAlert |
           UNAuthorizationOptionSound | UNAuthorizationOptionBadge;
           [[UNUserNotificationCenter currentNotificationCenter]
            requestAuthorizationWithOptions:authOptions
            completionHandler:^(BOOL granted, NSError * _Nullable error) {
                // ...
            }];
       }

    } else {
        // iOS 10 notifications aren't available; fall back to iOS 8-9 notifications.
        UIUserNotificationType allNotificationTypes =
        (UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge);
        UIUserNotificationSettings *settings =
        [UIUserNotificationSettings settingsForTypes:allNotificationTypes categories:nil];
        [application registerUserNotificationSettings:settings];
    }
    
    [application registerForRemoteNotifications];
    
//    [[FIRInstanceID instanceID] instanceIDWithHandler:^(FIRInstanceIDResult * _Nullable result,
//                                                        NSError * _Nullable error) {
//        if (error != nil) {
//            NSLog(@"Error fetching remote instance ID: %@", error);
//        } else {
//            NSLog(@"Remote instance ID token: %@", result.token);
//            NSString* message =
//            [NSString stringWithFormat:@"Remote InstanceID token: %@", result.token];
//            self.instanceIDTokenMessage.text = message;
//        }
//    }];
    
    return YES;
}

- (void)messaging:(FIRMessaging *)messaging didReceiveRegistrationToken:(NSString *)fcmToken {
    NSLog(@"FCM registration token fcmToken : %@", fcmToken);
    // Notify about received token.
    NSDictionary *dataDict = [NSDictionary dictionaryWithObject:fcmToken forKey:@"token"];
    [[NSNotificationCenter defaultCenter] postNotificationName:
     @"FCMToken" object:nil userInfo:dataDict];
    
    [DataPersist writeValuePre:fcmToken key:@"fcmToken"];
    // TODO: If necessary send token to application server.
    // Note: This callback is fired at each app startup and whenever a new token is generated.
}

//-(void)application:(UIApplication *)application handleActionWithIdentifier:(NSString *)identifier forLocalNotification:(UILocalNotification *)notification completionHandler:(void (^)())completionHandler{
//    if ([identifier isEqualToString:@"www.imooc.com.testmessage.lp"]) {
//        NSLog(@"抓紧回电话");
//    }else if([identifier isEqualToString:@"www.imooc.com.testmessage.leader"]){
//        NSLog(@"改bug 拉黑");
//    }
//}
// 1 app 后台模式:活着 内容 页面：xib sb ｜ 代码  接收到本地推送
-(void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification{

     NSDictionary *dic = notification.userInfo;
     UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 414, 736)];
     label.backgroundColor = [UIColor orangeColor];
     label.numberOfLines = 0;
     label.text = [NSString stringWithFormat:@"%@",dic];
     [self.window.rootViewController.view addSubview:label];
     NSLog(@"%@",dic);

    /*
     UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
     UIViewController *vc = [sb instantiateInitialViewController];
     self.window.rootViewController = vc;
     [self.window makeKeyAndVisible];
     */
//    MyViewController *vc = [[MyViewController alloc]init];
//    vc.view.backgroundColor = [UIColor orangeColor];
//    self.window.rootViewController = vc;
//    [self.window makeKeyAndVisible];
}



// [START receive_message]
//-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo{
//    UILabel *lab = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 320, 568)];
//    lab.backgroundColor = [UIColor greenColor];
//    lab.numberOfLines = 0;
//    lab.text = [NSString stringWithFormat:@"%@",userInfo];
//    [self.window.rootViewController.view addSubview:lab];
//    [self.window makeKeyAndVisible];
//
//
//    //FCM
//    // If you are receiving a notification message while your app is in the background,
//    // this callback will not be fired till the user taps on the notification launching the application.
//    // TODO: Handle data of notification
//
//    // With swizzling disabled you must let Messaging know about the message, for Analytics
//    // [[FIRMessaging messaging] appDidReceiveMessage:userInfo];
//
//    // Print message ID.
//    if (userInfo[kGCMMessageIDKey]) {
//        NSLog(@"Message ID: %@", userInfo[kGCMMessageIDKey]);
//    }
//
//    // Print full message.
//
//    NSLog(@"%@", userInfo);
//}

//- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
//fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
//    // If you are receiving a notification message while your app is in the background,
//    // this callback will not be fired till the user taps on the notification launching the application.
//    // TODO: Handle data of notification
//
//    // With swizzling disabled you must let Messaging know about the message, for Analytics
//    // [[FIRMessaging messaging] appDidReceiveMessage:userInfo];
//
//    // Print message ID.
//    if (userInfo[kGCMMessageIDKey]) {
//        NSLog(@"Message ID: %@", userInfo[kGCMMessageIDKey]);
//    }
//
//    // Print full message.
//    NSLog(@"%@", userInfo);
//
//    completionHandler(UIBackgroundFetchResultNewData);
//}



- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    NSLog(@"普通遠程推送");
     // iOS6及以下系统
    
    //FCM
    // If you are receiving a notification message while your app is in the background,
    // this callback will not be fired till the user taps on the notification launching the application.
    // TODO: Handle data of notification
    
    // With swizzling disabled you must let Messaging know about the message, for Analytics
    // [[FIRMessaging messaging] appDidReceiveMessage:userInfo];
    
    // Print message ID.
    if (userInfo[kGCMMessageIDKey]) {
        NSLog(@"Message ID: %@", userInfo[kGCMMessageIDKey]);
    }
    
    // Print full message.
    
    NSLog(@"%@", userInfo);
    
    // iOS6及以下系统
    if (userInfo) {
        if ([UIApplication sharedApplication].applicationState == UIApplicationStateActive) {// app位于前台通知
            NSLog(@"app位于前台通知(didReceiveRemoteNotification:):%@", userInfo);
        } else {// 切到后台唤起
            NSLog(@"app位于后台通知(didReceiveRemoteNotification:):%@", userInfo);
        }
    }
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler NS_AVAILABLE_IOS(7_0) {
     NSLog(@"后台推送的回调 静默推送");
    //后台推送的回调
    // iOS7及以上系统
    
    // If you are receiving a notification message while your app is in the background,
    // this callback will not be fired till the user taps on the notification launching the application.
    // TODO: Handle data of notification
    
    // With swizzling disabled you must let Messaging know about the message, for Analytics
    // [[FIRMessaging messaging] appDidReceiveMessage:userInfo];
    
    // Print message ID.
    if (userInfo[kGCMMessageIDKey]) {
        NSLog(@"Message back ID: %@", userInfo[kGCMMessageIDKey]);
    }
    
   
    
    NSDictionary *getDic = userInfo;
    NSString *notitype = [getDic valueForKey:@"type"];
    NSLog(@"notitype : %@",notitype);

    if([notitype isEqualToString:@"alarm_alert"]){  //预约本地推送
      
        NSString *apiurl = [getDic valueForKey:@"api"];
        //NSString *apiurl = @"http://youngplus.com.hk/app-get-schedule/?client=17189942025&start=2019-4-12&end=2019-4-12&test=1";
        NSLog(@"apiurl: %@", apiurl);
        //3.分隔字符串
        NSArray *array2 = [apiurl componentsSeparatedByString:@"?"]; //从字符A中分隔成2个元素的数组
        NSLog(@"array:%@",array2); //结果是adfsfsfs和dfsdf
        
        NSString *schedule = [array2 objectAtIndex:1];
        NSArray *schedulear = [schedule componentsSeparatedByString:@"&"]; //从字符A中分隔成2个元素的数组
        NSLog(@"schedulear:%@",schedulear); //结果是adfsfsfs和dfsdf
        
        NSString *client = [schedulear objectAtIndex:0];
        NSArray *clientarray = [client componentsSeparatedByString:@"="]; //从字符A中分隔成2个元素的数组
        NSLog(@"clientarray:%@",clientarray); //结果是adfsfsfs和dfsdf
        
        NSString *startstr = [schedulear objectAtIndex:1];
        NSArray *startarray = [startstr componentsSeparatedByString:@"="]; //从字符A中分隔成2个元素的数组
        NSLog(@"startarray:%@",startarray);
        
        NSString *endstr = [schedulear objectAtIndex:2];
        NSArray *endarray = [endstr componentsSeparatedByString:@"="]; //从字符A中分隔成2个元素的数组
        NSLog(@"endarray:%@",endarray);
        
        NSMutableDictionary *scheduleparams = [[NSMutableDictionary alloc]init];
        
        [scheduleparams setValue:[array2 objectAtIndex:0] forKeyPath:@"gourl"];
        [scheduleparams setValue:[clientarray objectAtIndex:0] forKeyPath:@"client1"];
        [scheduleparams setValue:[clientarray objectAtIndex:1] forKeyPath:@"client2"];
        
        [scheduleparams setValue:[startarray objectAtIndex:0] forKeyPath:@"start1"];
        [scheduleparams setValue:[startarray objectAtIndex:1] forKeyPath:@"start2"];
        
        [scheduleparams setValue:[endarray objectAtIndex:0] forKeyPath:@"end1"];
        [scheduleparams setValue:[endarray objectAtIndex:1] forKeyPath:@"end2"];
        
        NSLog(@"scheduleparams:%@",scheduleparams);
        
        [DataPersist writeValueNSMutableDictionary:scheduleparams key:@"scheduleparams"];

        /**  单个字符串截取
        NSRange startRange = [apiurl rangeOfString:@"?"];
        NSRange endRange = [apiurl rangeOfString:@"&"];
        NSRange range = NSMakeRange(startRange.location + startRange.length, endRange.location - startRange.location - startRange.length);
        NSString *result = [apiurl substringWithRange:range];
        NSLog(@"%@",result);
         */
        
        setLocalnoti *younglocalnoti = [[setLocalnoti alloc]init];
        [younglocalnoti setnetdataNoti];
     
//        setLocalnoti *younglocalnoti = [[setLocalnoti alloc]init];  //设置本地通知
////        UINavigationController *nav = (UINavigationController *)self.window.rootViewController;
////        //testVc2 *vc = [[testVc2 alloc]init];
////        [nav pushViewController:younglocalnoti animated:YES];
//        [younglocalnoti setnetdataNoti];
        
    }
    // Print full message.
    //NSLog(@"%@", userInfo);
    
    //completionHandler(UIBackgroundFetchResultNewData);
    
    // iOS7及以上系统
    if (userInfo) {
        if ([UIApplication sharedApplication].applicationState == UIApplicationStateActive) {
            NSLog(@"app位于前台通知(didReceiveRemoteNotification:fetchCompletionHandler:):%@", userInfo);
        } else {
            NSLog(@"app位于后台通知(didReceiveRemoteNotification:fetchCompletionHandler:):%@", userInfo);
        }
    }
    completionHandler(UIBackgroundFetchResultNewData);
}


#pragma mark - iOS>=10 中收到推送消息

#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0

- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler
API_AVAILABLE(ios(10.0)){
    NSDictionary * userInfo = notification.request.content.userInfo;
    if (userInfo) {
        NSLog(@"app位于前台通知(willPresentNotification:):%@", userInfo);
    }
    completionHandler(UNNotificationPresentationOptionBadge|UNNotificationPresentationOptionSound|UNNotificationPresentationOptionAlert);
    
    //接收FCM远程通知
    // Print message ID.
    if (userInfo[kGCMMessageIDKey]) {
        NSLog(@"Message ID: %@", userInfo[kGCMMessageIDKey]);
    }
    
    // Print full message.
    NSLog(@"接收本地/远程通知 :%@", userInfo);
    
    
    // 获取消息内容
    NSMutableDictionary *content = [[NSMutableDictionary alloc] init];
    [content setObject:notification.request.content.title forKey:@"content"];
    [content setObject:notification.request.content.body forKey:@"body"];
    
    // 判断是否为本地通知
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        NSLog(@"willPresentNotification 收到远程通知");
    } else {
        NSLog(@"willPresentNotification 判断为本地通知");
        // 判断为本地通知
        //创建通知对象
//        NSNotification *notice = [NSNotification notificationWithName:@"ReadNoticeContent" object:nil userInfo:content];
//        //发送通知
//        [[NSNotificationCenter defaultCenter] postNotification:notice];
    }
    
    // Change this to your preferred presentation option
    completionHandler(UNNotificationPresentationOptionNone);
    
}

- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)(void))completionHandler
API_AVAILABLE(ios(10.0)){
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    if (userInfo) {
        NSLog(@"点击通知进入App时触发(didReceiveNotificationResponse:):%@", userInfo);
         [self RemoteNotishowAlert];
    }
    if (userInfo[kGCMMessageIDKey]) {  //远程推送
        NSLog(@"Message ID: %@", userInfo[kGCMMessageIDKey]);
        
        NSLog(@"远程推送触发calertcon");
        
        [self RemoteNotishowAlert];
    }
    
    // Print full message.
    NSLog(@"didReceiveNotificationResponse %@", userInfo);
    
    
    completionHandler(); // 系统要求执行这个方法

}

#endif



// [END receive_message]

- (void)RemoteNotishowAlert
{
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"是否去消息界面" message:@"请选择" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *alertAction = [UIAlertAction actionWithTitle:@"跳转" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        // 跳转页面 跳转到消息列表页面
//        ViewController *viewC = [[ViewController alloc] init];
//        [AppDelegate myPushViewController:viewC];
        NSLog(@"点击了确定，准备push");
        
        [self gomyPush];
    }];
    UIAlertAction *doneAction = [UIAlertAction actionWithTitle:@"已完成" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        // 跳转页面 跳转到消息列表页面
//        ViewController *viewC = [[ViewController alloc] init];
//        [AppDelegate myPushViewController:viewC];
        NSLog(@"点击了已完成，准备push");
    }];
    UIAlertAction *undoneAction = [UIAlertAction actionWithTitle:@"未完成" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        // 跳转页面 跳转到消息列表页面
//        ViewController *viewC = [[ViewController alloc] init];
//        [AppDelegate myPushViewController:viewC];
        NSLog(@"点击了未完成，准备push");
    }];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    [alertController addAction:alertAction];
    [alertController addAction:doneAction];
    [alertController addAction:undoneAction];
    [alertController addAction:cancelAction];
   // [self.myNavigationController presentViewController:alertAction animated:YES completion:nil];
       [self.window.rootViewController presentViewController:alertController animated:YES completion:nil];  // 因为self.window.rootViewController = self.myNavigationController，所以这两个方法是一样的
   // [time invalidate];
}

-(void)gomyPush{  //AppDelegate 跳转其他视图控制器
        UINavigationController *nav = (UINavigationController *)self.window.rootViewController;
        testVc2 *vc = [[testVc2 alloc]init];
        [nav pushViewController:vc animated:YES];
}

+ (void)myPushViewController:(UIViewController *)controller
{
//    UINavigationController *nvc = myDelegate().myNavigationController;
//    [nvc pushViewController:controller animated:YES];
    
//    // 应用在后台点击通知，直接跳转 web 页面
////    NSString *url = userInfo[@"url"];
////    if (url)
////    {
//        UINavigationController *nav = self.window.rootViewController;
//        WebViewController *webVC = [[WebViewController alloc] init];
//        webVC.url = url;
//        [nav pushViewController:webVC animated:YES];
////    }
////    ---------------------
////    作者：pipimob
////    来源：CSDN
////    原文：https://blog.csdn.net/pipimob/article/details/80062203
////    版权声明：本文为博主原创文章，转载请附上博文链接！
 
//    UINavigationController *nav = (UINavigationController *)self.window.rootViewController;
//    WebViewController *webVC = [[WebViewController alloc] init];
//    webVC.url = url;
//    [nav pushViewController:webVC animated:YES];
    
    
//    testVc2 *vc = [[testVc2 alloc]init];
//    vc.view.backgroundColor = [UIColor orangeColor];
//    self.window.rootViewController = vc;
//    [self.window makeKeyAndVisible];
    
    
    
//    LoginViewController3 *messageVC = [[LoginViewController3 alloc] init];
//
//    UINavigationController *navi = [[UINavigationController alloc]initWithRootViewController:messageVC];
//
//    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
//    self.window.rootViewController = [[UINavigationController alloc] initWithRootViewController:[[ViewController alloc] init]];
//    [self.window makeKeyAndVisible];
//    self.window.backgroundColor = [UIColor whiteColor];
}
// 当然，你也可以不用那么繁琐，直接用[self .myNavigationController pushViewController:controller animated:YES];  // push到想要跳转的控制器即可


// [START ios_10_message_handling]
// Receive displayed notifications for iOS 10 devices.
// Handle incoming notification messages while app is in the foreground.
//- (void)userNotificationCenter:(UNUserNotificationCenter *)center
//       willPresentNotification:(UNNotification *)notification
//         withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler {
//    NSDictionary *userInfo = notification.request.content.userInfo;
//
//    // With swizzling disabled you must let Messaging know about the message, for Analytics
//    // [[FIRMessaging messaging] appDidReceiveMessage:userInfo];
//
//    //接收FCM远程通知
//    // Print message ID.
//    if (userInfo[kGCMMessageIDKey]) {
//        NSLog(@"Message ID: %@", userInfo[kGCMMessageIDKey]);
//    }
//
//    // Print full message.
//    NSLog(@"%@", userInfo);
//
//    // Change this to your preferred presentation option
//    completionHandler(UNNotificationPresentationOptionNone);
//}

// Handle notification messages after display notification is tapped by the user.
//- (void)userNotificationCenter:(UNUserNotificationCenter *)center
//didReceiveNotificationResponse:(UNNotificationResponse *)response
//         withCompletionHandler:(void(^)(void))completionHandler {
//    NSDictionary *userInfo = response.notification.request.content.userInfo;
//    if (userInfo[kGCMMessageIDKey]) {
//        NSLog(@"Message ID: %@", userInfo[kGCMMessageIDKey]);
//    }
//    
//    // Print full message.
//    NSLog(@"%@", userInfo);
//    
//    completionHandler();
//}


// [END ios_10_message_handling]

// [START refresh_token]
//- (void)messaging:(FIRMessaging *)messaging didReceiveRegistrationToken:(NSString *)fcmToken {
//    NSLog(@"FCM registration token: %@", fcmToken);
//    // Notify about received token.
//    NSDictionary *dataDict = [NSDictionary dictionaryWithObject:fcmToken forKey:@"token"];
//    [[NSNotificationCenter defaultCenter] postNotificationName:
//     @"FCMToken" object:nil userInfo:dataDict];
//    // TODO: If necessary send token to application server.
//    // Note: This callback is fired at each app startup and whenever a new token is generated.
//}
// [END refresh_token]




// [START ios_10_data_message]
// Receive data messages on iOS 10+ directly from FCM (bypassing APNs) when the app is in the foreground.
// To enable direct data messages, you can set [Messaging messaging].shouldEstablishDirectChannel to YES.
- (void)messaging:(FIRMessaging *)messaging didReceiveMessage:(FIRMessagingRemoteMessage *)remoteMessage {
    NSLog(@"Received data message: %@", remoteMessage.appData);
}
// [END ios_10_data_message]

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    NSLog(@"Unable to register for remote notifications: %@", error);
}

// This function is added here only for debugging purposes, and can be removed if swizzling is enabled.
// If swizzling is disabled then this function must be implemented so that the APNs device token can be paired to
// the FCM registration token.
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    
    // ip6s   ce5784be 70d6d760 9f264298 e6a05b6c 0287ebca 17bca417 8059bbe1 ae2fa6b8
    //XR ce8afa2b c2713658 5c43e989 51d553b9 1b91ff43 82eb3750 4706bfcc ecd06edc
    //ce8afa2bc27136585c43e98951d553b91b91ff4382eb37504706bfccecd06edc
    //NSLog(@"%@",deviceToken);
    NSLog(@"APNs device token retrieved: %@", deviceToken);
    
    // With swizzling disabled you must set the APNs device token here.
    // [FIRMessaging messaging].APNSToken = deviceToken;
}

/**
 本地通知
 */




- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings {
    
    NSLog(@"didRegisterUserNotificationSettings");
}

//- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
//
//    NSLog(@"app收到本地推送(didReceiveLocalNotification:):%@", notification.userInfo);
//}
//
//- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
//
//    // 获取并处理deviceToken
//    NSString *token = [[deviceToken description] stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]];
//    token = [token stringByReplacingOccurrencesOfString:@" " withString:@""];
//    NSLog(@"DeviceToken:%@\n", token);
//}
//
//- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
//
//    NSLog(@"didFailToRegisterForRemoteNotificationsWithError: %@", error.description);
//}

// 注：iOS10以上如果不使用UNUserNotificationCenter时，也将走此回调方法



//// apsModel示例
/*
 特殊说明：
 1. APNS去掉alert、badge、sound字段实现静默推送，增加增加字段"content-available":1，也可以在后台做一些事情。
 2. mutable-content这个键值为1，说明此条推送可以被 Service Extension 进行更改。
 */

/**
 {"aps":{"alert":{"title":"通知的title","subtitle":"通知的subtitle","body":"通知的body","title-loc-key":"TITLE_LOC_KEY","title-loc-args":["t_01","t_02"],"loc-key":"LOC_KEY","loc-args":["l_01","l_02"]},"sound":"sound01.wav","badge":1,"mutable-content":1,"category": "QiShareCategoryIdentifier"},"msgid":"123"}
 */

/**
 {"aps":{"alert":{"title":"Title...","subtitle":"Subtitle...","body":"Body..."},"sound":"default","badge": 1,"mutable-content": 1,"category": "QiShareCategoryIdentifier",},"msgid":"123","media":{"type":"image","url":"https://www.fotor.com/images2/features/photo_effects/e_bw.jpg"}}
 */
/**
 本地通知
 */


//键盘add Done
-(void) addDoneToKeyboard:(UITextField *) textField {
    
    UIToolbar* keyboardToolbar = [[UIToolbar alloc] init];
    
    [keyboardToolbar sizeToFit];
    
    UIBarButtonItem *flexBarButton = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
    
    UIBarButtonItem *doneBarButton = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(DoneButtonPressed:)];
    
    [doneBarButton setTitle:@"輸入"];

    keyboardToolbar.items = @[flexBarButton, doneBarButton];
    
    textField.inputAccessoryView = keyboardToolbar;
    
}
-(void) DoneButtonPressed:(UIBarButtonItem *)b {
    [self.window.rootViewController.view endEditing:YES];
}
    


- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

-(UIImage *) getImage:(NSString *)key callback:(void (^)(UIImage *image))callback {
    
    NSArray *parts = [key componentsSeparatedByString:@"/"];
    NSString *filename = [parts lastObject];
    
    if (filename != nil && ![filename isEqual:[NSNull null]]) {
        
        // NSLog(@"Retrieving %@",key);
        
        UIImage * _cachedImage = [[UIImage alloc]init];//(UIImage *)[imageCache objectForKey:filename];
        
        if (!_cachedImage) {
            
            //          NSLog(@"Not found.. loading from url.. %@",filename);
            
            if (callback !=nil) {
                
                dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0ul);
                
                dispatch_async(queue, ^{
                    
                    // NSData * imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:key]];
                    
                    UIImage *image = [self downloadImage:key];
                    
                    if (image) {
                        
                        // [imageCache setObject:image forKey:filename];
                        
                    }
                    
                    dispatch_async(dispatch_get_main_queue(), ^{
                        
                        //   UIImage *image = [UIImage imageWithData:imageData];
                        
                        if (callback) {
                            
                            if (image) {
                                
                                callback(image);
                                
                            } else {
                                
                                NSLog(@"AD getImage warning image is null %@",filename);
                                
                            }
                            
                        }
                        
                    });
                    
                });
                
                _cachedImage = [UIImage imageNamed:@"placeholder.png"];
                
            } else {
                
                _cachedImage = [self downloadImage:key];
                
                if (_cachedImage) {
                    
                    // [imageCache setObject:_cachedImage forKey:filename];
                    
                }
                
            }
            
        } else {
            
            // NSLog(@"found in cache.. %@",key);
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                //   UIImage *image = [UIImage imageWithData:imageData];
                
                if (callback) {
                    
                    callback(_cachedImage);
                    
                }
                
            });
            
        }
        
        return _cachedImage;
        
    } else {
        
        return nil;
        
    }
    
}

-(UIImage *) downloadImage:(NSString *) url {
    
    
    
    // Get an image from the URL below
    
    //    NSString *utf8url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    NSArray *parts = [url componentsSeparatedByString:@"/"];
    
    NSString *filename = [parts lastObject];
    
    NSString *path = [url stringByReplacingOccurrencesOfString:filename withString:@""];
    
//    NSString *utf8url = [NSString stringWithFormat:@"%@%@",path,[filename stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
//    NSLog(@"utf8url : %@",utf8url);
    
    NSString *utf8url = [NSString stringWithFormat:@"%@%@",path,filename];
    utf8url = [utf8url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    NSLog(@"utf8url : %@",utf8url);
    
    NSURL *imageurl = [NSURL URLWithString:utf8url];
    
    UIImage *image = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:imageurl]];
    
    NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    
    
    
    NSArray *file = [filename componentsSeparatedByString:@"."];
    
    NSString *ext = [file lastObject];
    
    NSString *outputFilePath = [NSString stringWithFormat:@"%@/%@",docDir, filename];
    
    NSData *data2;
    
    if ([ext caseInsensitiveCompare:@"png"]==NSOrderedSame) {
        
        data2 = [NSData dataWithData:UIImagePNGRepresentation(image)];//1.0f = 100% quality
        
    } else {
        
        data2 = [NSData dataWithData:UIImageJPEGRepresentation(image, 1.0f)];//1.0f = 100% quality
        
        // NSLog(@"saving image done");
        
    }
    
    [data2 writeToFile:outputFilePath atomically:YES];
    
    return image;
}
//
//[delegate getImage:asdfasdf

@end
